import os
import time
import json
import requests
from wxauto import WeChat

# 加载历史消息记录
DB = {}
if os.path.exists("db.json"):
    fp = open("db.json", encoding='utf-8', mode='r')
    DB = json.load(fp)
    fp.close()

# 读取users.txt加载监听用户
MONITOR_LIST = []
if not os.path.exists("users.txt"):
    fp = open("users.txt", encoding="utf-8", mode='w')
    fp.close()
else:
    fp = open("users.txt", encoding="utf-8", mode='r')
    for line in fp:
        line = line.strip()
        if not line:
            continue
        MONITOR_LIST.append(line)
    fp.close()

# 1.打开微信
wx = WeChat()

# 2.监听账户列表（好友名称）
# MONITOR_LIST = ["武沛齐-已满-加wupeiqi888"]
for ele in MONITOR_LIST:
    wx.AddListenChat(who=ele)

# 3.监听消息
while True:
    listen_dict = wx.GetListenMessage()
    for chat_win, message_list in listen_dict.items():
        # print(chat_win.who)
        chat_user = chat_win.who

        # 获取最新聊天的消息
        interval_list = []
        for msg in message_list:
            if msg.type != "friend":
                continue
            interval_list.append({"role": "user", "content": msg.content})

        if not interval_list:
            continue

        # 拼接历史聊天记录
        print("微信消息：")
        for interval in interval_list:
            print(interval)

        history_list = DB.get(chat_user, [])
        history_list.extend(interval_list)

        # 调用本地deepseek模型
        res = requests.post(
            url="http://localhost:11434/api/chat",
            json={
                "model": "deepseek-r1:1.5b",
                "messages": history_list,
                "stream": False
            }
        )
        data_dict = res.json()
        res_msg_dict = data_dict['message']

        # 获取deepseek回复内容，微信回复
        res_content = res_msg_dict['content']
        chat_win.SendMsg(res_content)
        print("deepseek回复：")
        print(res_content)

        # 保存沟通记录
        history_list.append(res_msg_dict)
        DB[chat_user] = history_list
        with open("db.json", encoding='utf-8', mode='w') as fp:
            json.dump(DB, fp, ensure_ascii=False, indent=2)

